package edu.guigu.networkdemomvvm.nonsingle;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import edu.guigu.networkdemomvvm.R;
import edu.guigu.networkdemomvvm.databinding.ActivityMultBinding;

public class MultActivity extends AppCompatActivity {

    private ActivityMultBinding binding;
    private StateViewModel stateViewModel;
    private RequestViewModel requestViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_mult);
        binding.setLifecycleOwner(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        stateViewModel = new ViewModelProvider(this).get(StateViewModel.class);
        binding.setViewModel(stateViewModel);

        requestViewModel = new ViewModelProvider(this).get(RequestViewModel.class);
        requestViewModel.remoteUserList();
        showProgressDialog();
        requestViewModel.responseLiveData.observe(this, users -> {
            stateViewModel.addUserList(users);
            hideProgressDialog();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    private ProgressDialog progressDialog;

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在加载中...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}